import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  SirSelfCheckQuery,
  getSirSelfCheckListApi,
  exportSirSelfCheckExcelApi,
  deleteSirSelfCheckApi, getProfessionalApi
} from "@/api/airport/dataManage/sirSelfCheck";

export function useSafetyManageHook() {
  const defaultSort: Sort = {
    prop: "id",
    order: "ascending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.beginTime && searchFormParams.endTime) {
        return [searchFormParams.beginTime, searchFormParams.endTime];
      } else {
        return null;
      }
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.beginTime = v[0];
        searchFormParams.endTime = v[1];
      } else {
        searchFormParams.beginTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });

  const searchFormParams = reactive<SirSelfCheckQuery>({
    professional: "",
    checkContent: "",
    belongDept: undefined,
    tagId: undefined,

  });

  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);
  const sortState = ref<Sort>(defaultSort);

  const columns: TableColumnList = [
    { type: "selection", align: "left" }, // 保留选择框用于批量操作
    { label: "序号", prop: "seq", minWidth: 80 },
    { label: "专业板块", prop: "professional", minWidth: 120 },
    { label: "检查内容", prop: "checkContent", minWidth: 180, showOverflowTooltip: true },
    { label: "检查标准", prop: "checkStandard", minWidth: 180, showOverflowTooltip: true },
    { label: "符合性判定标准", prop: "complianceCriteria", minWidth: 160, showOverflowTooltip: true },
    { label: "检查方式", prop: "checkMethod", minWidth: 120 },
    { label: "公司依据", prop: "companyBasis", minWidth: 140, showOverflowTooltip: true },
    { label: "法律法规依据", prop: "lawsBasis", minWidth: 160, showOverflowTooltip: true },
    { label: "法律法规条款", prop: "lawsClause", minWidth: 160, showOverflowTooltip: true },
    { label: "融合来源", prop: "integrationSource", minWidth: 140 },
    { label: "检查涉及部门", prop: "checkDepartments", minWidth: 160 },
    { label: "归属部门", prop: "belongDeptName", minWidth: 160 },
    { label: "标签", prop: "tagName", minWidth: 160 },

    { label: "操作", fixed: "right", width: 230, slot: "operation" }
  ];

  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    pagination.currentPage = 1;
    getSirSelfCheckList();
  }

  async function onSearch(tableRef) {
    tableRef.getTableRef().sort("id", "ascending");
    getSirSelfCheckList(); // 添加此行触发数据加载
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    formEl.resetFields();
    searchFormParams.beginTime = undefined;
    searchFormParams.endTime = undefined;
    onSearch(tableRef);
  }

  async function getSirSelfCheckList() {
    pageLoading.value = true;
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);

    const { data } = await getSirSelfCheckListApi(toRaw(searchFormParams)).finally(() => {
      pageLoading.value = false;
    });

    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function exportAllExcel() {
    if (sortState.value != null) {
      CommonUtils.fillSortParams(searchFormParams, sortState.value);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    exportSirSelfCheckExcelApi(toRaw(searchFormParams), "自查事项数据.xlsx");
  }

  async function handleDelete(row) {
    await deleteSirSelfCheckApi([row.id]).then(() => { // 单个ID仍使用数组包裹
      message(`您删除了编号为 ${row.id} 的自查事项`, {
        type: "success"
      });
      getSirSelfCheckList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的自查事项吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteSirSelfCheckApi(multipleSelection.value).then(() => { // multipleSelection.value本身就是ID数组
          message(`您删除了编号为 [ ${multipleSelection.value} ] 的自查事项`, {
            type: "success"
          });
          getSirSelfCheckList();
        });
      })
      .catch(() => {
        message("取消删除", { type: "info" });
        tableRef.getTableRef().clearSelection();
      });
  }

  onMounted(getSirSelfCheckList);

  const professionalOptions = ref<string[]>([]);

  // 获取专业列表数据
  const loadProfessionalOptions = async () => {
    try {
      // 从响应中提取data字段中的专业列表数组
      const { data } = await getProfessionalApi();
      // 正确获取嵌套在data属性中的专业列表
      professionalOptions.value = data || [];
    } catch (error) {
      // message.error("获取专业列表失败");
      // professionalOptions.value = [];
    }
  };

  // 在组件挂载时加载专业列表
  onMounted(() => {
    loadProfessionalOptions();
  });

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    timeRange,
    multipleSelection,
    onSearch,
    onSortChanged,
    exportAllExcel,
    getSirSelfCheckList,
    resetForm,
    handleDelete,
    handleBulkDelete,
    professionalOptions
  };
}
